﻿/******************************************************   
创建者: ljj
创建时间: 2018-07-19
修改:
修改时间: 
功能: 评分结果
 ******************************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using com.kmer.ApiServer;
using ZXing;
using ZXing.QrCode;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using com.kmer;
using com.kmer.ApiServer.Attributes;
using com.kmer.Attributes;
using com.kmer.db;
using com.kmer.Helper;
using kmer.Data;
using TouchUIWeiXinAPI.model;
using System.Net;

namespace TouchUIWeiXinAPI
{
    /// <summary>
    /// 微信生成二维码
    /// </summary>
    public class WXOrderResultHandler : WXBaseHandler
    {
        /// writer:ljj
        /// Create Date：2018-07-20
        [Description("评分结果")]
        [ReturnType(typeof(PaperData<OrderModel.OrderResultModel>))]
        public ApiResult GetOrderResultList([ParamDescription("订货会ID")] int? MasterID = null,
            [ParamDescription("OpenId")] string OpenId = "", [ParamDescription("系列")] string SerialName = "",
            [ParamDescription("项目")] string ItemName = "", [ParamDescription("排序(1-从高到低,0-从低到高)")] int Sort = 1,
            [ParamDescription("页码")] int Page = 1, [ParamDescription("页数")] int Size = 20)
        {
            try
            {
                if (!MasterID.HasValue) return Error("订货会内码ID不能为空!");
                if (string.IsNullOrEmpty(OpenId)) return Error("OpenID不能为空!");
                var companyID = this.CompanyID;
                var dc = new km_platformEntities();
                var user = dc.t_order_wx_account.FirstOrDefault(
                    d => d.OpenId == OpenId && !d.IsDisable && !d.IsRemove &&
                         (d.AccountType == 0 ||d.AccountType == 1 || d.AccountType == 3));
                if (user == null) return Error("该用户没有权限!");
                var newItemStr = "";
                if (!string.IsNullOrEmpty(ItemName))
                {
                    var itemList = ItemName.Split(',');
                    var newItemList = new List<string>();
                    foreach (var item in itemList)
                    {
                        newItemList.Add("''" + item + "''");
                    }
                    newItemStr = string.Join(",", newItemList);
                }
                var sql = $@"
EXEC	[km_platform].[dbo].[wx_order_Result]
		@CompanyID = '{companyID}',
		@ExtrSource = '{companyID}',
		@MasterID = '{MasterID}',
		@SerialName = '{SerialName}',
		@ItemName = '{newItemStr}',
		@Sort = {Sort},
        @OpenID = '{OpenId}'";
                //'IN (''aaa'',''bbb'')'
                var query = dc.Database.SqlQuery<OrderModel.OrderResultModel>(sql);
                var result = PaperData<OrderModel.OrderResultModel>.Create(query.Count(), Size, Page);
                var list = query.Skip(result.Skip)
                    .Take(result.Limt).ToList();
                foreach (var item in list)
                {
                    item.ImgUrl = item.SerialNo == null
                        ? "http://tsf.erp-km.cn:9005/assets/weixin/upload.png"
                        : GetWXImageUrlV3(dc, item.MasterID, item.SerialNo);
                }
                result.Items = list;
                return Success(result);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }


        /// <summary>
        /// 获取待审商品列表V2 api 中的图片地址
        /// </summary>
        /// <param name="request"></param>
        /// <param name="MasterID">订货会ID</param>
        /// <param name="SerialNo">流水号</param>
        /// <returns></returns>
        private string GetWXImageUrlV3(km_platformEntities dc, int MasterID, string SerialNo)
        {
            var query = dc.kmImages.FirstOrDefault(d => d.Title == (MasterID + "/" + SerialNo));
            if (query != null)
            {
                var url = $"http://kmer-online-pic.oss-cn-shenzhen.aliyuncs.com/OrderApp/{MasterID}/{SerialNo}.jpg";
                if (RemoteFileExists(url))
                {
                    return url;
                }
            }
            return "http://tsf.erp-km.cn:9005/assets/weixin/upload.png";
        }

        private bool RemoteFileExists(string fileUrl)
        {
            bool result = false;//下载结果

            WebResponse response = null;
            try
            {
                WebRequest req = WebRequest.Create(fileUrl);

                response = req.GetResponse();

                result = response == null ? false : true;

            }
            catch (Exception ex)
            {
                result = false;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }

            return result;
        }

        /// writer：ljj
        /// date：2018-07-20
        [MustLogin]
        [JsonType]
        [Description("保存评分结果")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult Save([ParamDescription("评分结果")] OrderModel.LevelSaveModel param)
        {
            try
            {
                if (param == null) return Error("参数对象为空");
                if (string.IsNullOrEmpty(param.OpenId)) return Error("OpenID不能为空!");
                var dc = new km_platformEntities();
                var user = dc.t_order_wx_account.FirstOrDefault(
                    d => d.OpenId == param.OpenId && !d.IsDisable && !d.IsRemove &&
                         (d.AccountType == 0 || d.AccountType == 3));
                if (user == null) return Error("该用户没有权限!");
                if (param.levelList != null)
                {
                    var companyID = this.CompanyID;
                    foreach (var item in param.levelList)
                    {
                        var query = dc.t_order_Fashion_level.FirstOrDefault(
                            d => d.MasterID == item.MasterID && d.SerialNo == item.SerialNo &&
                                 d.CompanyID == companyID);
                        if (query == null)
                        {
                            dc.t_order_Fashion_level.Add(new t_order_Fashion_level
                            {
                                UserID = -1,
                                CompanyID = companyID,
                                ExtrSource = companyID,
                                AStoreLevel = item.AStoreLevel,
                                BStoreLevel = item.BStoreLevel,
                                MasterID = item.MasterID,
                                SerialNo = item.SerialNo,
                                UpdateTime = DateTime.Now,
                                OpenId = param.OpenId,
                            });
                        }
                        else
                        {
                            query.UserID = -1;
                            query.CompanyID = companyID;
                            query.ExtrSource = companyID;
                            query.AStoreLevel = item.AStoreLevel;
                            query.BStoreLevel = item.BStoreLevel;
                            query.UpdateTime = DateTime.Now;
                            query.OpenId = param.OpenId;
                        }
                    }
                    dc.SaveChanges();
                }
                return Success(0);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }
    }
}
